$(function(){
	var $cateModal = $('#category-edit-modal');	
	var $friModal = $('#friend-edit-modal');
	var $friTypeContainer = $('.cooperater-type-container');
	var firTypeTplStr = $('#fri-type-tpl').html();
	var firTplStr = $('#preview-tpl').html();

	function Editor() {
	}
	Editor.prototype = {
		$ele: null,
		init: function($ele) {
			this.$ele = $ele;
			var $ele = this.$ele;
			var self = this;
			$ele.find('.save-btn').on('click',function(){
				self.saveFunc();	

			});
			$ele.modal({
				backdrop: 'static',
				show: false
			});
		},
		setTitle: function(title) {
			this.$ele.find('.modal-title').html(title);
		},
		setData: function(obj) {
			for(key in obj) {
				var $ele = this.$ele.find('[data-role="'+key+'"]');
				var value = obj[key];
				if(key == 'image') {
					$ele.css('background-image','url('+ value +')');
				} else {
					$ele.val(value);	
				}
			}
		},
		getData: function() {
			var result = {
			};
			this.$ele.find('[data-role]').each(function(){
				var $this = $(this);
				var key = $this.attr('data-role');
				var value = null;
				if( key == 'image' ) {
					if($this.css('background-image').indexOf("\"")==-1){
						value = $this.css('background-image').match(/url\((.*)\)/)[1];
					}else{
						value = $this.css('background-image').match(/url\("(.*)"\)/)[1];
					}
					//value = $this.css('background-image').match(/url\((.*)\)/)[1]; 
					//value = $this.css('background-image');
					//value = value.substring(4,value.length-2);
				} else {
					value = $this.val();
				}
				result[key]=value;
			});
			return result;
		},
		hide: function() {
			this.$ele.modal('hide');
	    },
		show: function() {
			this.$ele.modal('show');
	    }
	}

	function CateEditor($ele) {
		this.init($ele);
		var cateEditor  = this;
		var $ele = this.$ele;
	}	
	CateEditor.prototype = new Editor();
	$.extend(CateEditor.prototype,{
		typeId: null,
		saveFunc: null,
		show: function(obj) {
			if(obj) {
				this.setTitle('编辑合作伙伴分类');
			} else {
				this.setTitle('新建合作伙伴分类');
			}
			Editor.prototype.show.call(this);
		}
	});


	function getEleByRoleName($ele,rolename) {
		return $ele.find('[data-role="'+rolename+'"]');
	}
	
	function PageItem() {
	}
	PageItem.prototype = {
		init: function($ele) {
			this.$ele = $ele;
		},
		getDataUrl: null,
		setData: function(obj) {
			this.$ele.data({cmsData:obj});						
			this.rend(obj);
		},
		rend: function(obj) {
			var $ele = this.$ele;
			for(var key in obj) {
				var value = obj[key];
				if(key == 'image') {
					getEleByRoleName($ele,key).css('background-image','url('+value+')');
				} else {
					getEleByRoleName($ele,key).html(value);
				}
			}
		},
		getData: function(callback) {
			var self = this;
			var data = this.$ele.data('cmsData');
			if(data){
				callback(data);
			} else {
				cAjax({
					type: 'get',
					url: self.getDataUrl,
					data: {
						id: self.$ele.attr('data-id')
					},
					success: function(obj) {
						self.setData(obj['data']);
						callback(obj['data']);
					}
				});
			}
		}
	}

	function Cate($ele) {
		this.$ele = $ele;
		PageItem.prototype.init.call(this,$ele);
	}
	Cate.prototype = new PageItem();
	$.extend(Cate.prototype,{
		getDataUrl: '/web/home/cooperater/getCooperaterType'
	});

	function Fri($ele) {
		this.$ele = $ele;
		PageItem.prototype.init.call(this,$ele);
	}
	Fri.prototype = new PageItem();
	$.extend(Fri.prototype,{
		getDataUrl: '/web/home/cooperater/getCooperater',
		setData: function(obj) {
			this.$ele.css('background-image','url("'+obj['image']+'")');
			PageItem.prototype.setData.call(this,obj);

		}
	});


	function FriEditor($ele) {
		this.init($ele);
		var $friendLogo = $ele.find('.friend-logo');
		$friendLogo.on('click',function(){
			var $this = $(this);
			var uploader = new PicUploader({
				success: function(obj){
					$this.css('background-image','url("'+obj['data']+'")');
				}
			});
			uploader.start();

		});
	}	
	FriEditor.prototype = new Editor();
	$.extend(FriEditor.prototype,{
		show: function(isNew){
			if(isNew) {
				this.setTitle('新建合作伙伴');
			} else {
				this.setTitle('编辑合作伙伴');
			}
			Editor.prototype.show.call(this);
		}
	});

	var cateEditor = new CateEditor($cateModal);
	var friEditor = new FriEditor($friModal);

	$('#new-category-btn').on('click',function(){
		cateEditor.setData({
			name: ''
		});
		cateEditor.show();
		cateEditor.saveFunc = function() {
			var formData = cateEditor.getData();
			cAjax({
				url: '/web/home/cooperater/addCooperaterType',
				data: formData, 
				success: function(obj) {
					var $newFriTypeEle = $(firTypeTplStr)
					var cate = new Cate($newFriTypeEle);	
					cate.setData(cateEditor.getData());
					$friTypeContainer.append($newFriTypeEle);
					cateEditor.hide();
					window.location.reload();
				}
			});
		}
	});

	$friTypeContainer.on('click','.del-btn',function(){
		var $ele = $(this).parents('.box');
		var cate = new Cate($ele);	
		actionConfirm({
			msg: '确定删除这个分类吗？',
			confirm: function(){
				cate.getData(function(data){
					cAjax({
						url: '/web/home/cooperater/deleteCooperaterType',
						data: {
							id: data['id'] 
						},
						success: function(obj) {
							$ele.remove();	

							greeting({
								msg: "分类已删除"
							});
						}
					});
				});	
			}
		});
	});


	$friTypeContainer.on('click','.edit-btn',function(){	
		var cate = new Cate($(this).parents('.box'));
		var $this = $(this);
		cateEditor.saveFunc = function() {
			cate.getData(function(data){
				var cateData = cateEditor.getData();
				var formData = {
					id: data['id'],
					name: cateData['name']
				};

				cAjax({
					url: '/web/home/cooperater/editCooperaterType',
					data: formData, 
					success: function(obj) {
						cate.setData(cateEditor.getData());
						cateEditor.hide();
					}
				});
			});

		}
		cate.getData(function(obj){
			cateEditor.setData(obj);
			cateEditor.show(obj);
		});
	});
	
	/**
	 * 保存首页合作伙伴
	 */
	$("#save-home-sorts-btn").on("click", function(){
		var $items = $(".cooperater-on-homepage").find(".preview");
		var homeIds = new Array();
		var sorts = new Array();
		if($items.length==0){
			greeting({msg:"请先添加数据"});
			return false;
		}
		$items.each(function(i){
			homeIds[i] = $(this).data("id");
			sorts[i] = i + 1;
		});
		cAjax({
			url: '/web/home/cooperater/saveHomeSorts',
			type:'post',
			data: {'homeIds':homeIds,'sorts':sorts},
			success:function(obj){
				greeting({msg:"保存成功"});
			},
			error: function(obj) {
			}
		});
	});
	
	/**
	 * 保存顺序
	 */
	$("#save-type-sorts-btn").on("click", function(){
		var $items = $friTypeContainer.find(".cooperater-type");
		var typeIds = new Array();
		var sorts = new Array();
		if($items.length==0){
			greeting({msg:"请先添加数据"});
			return false;
		}
		$items.each(function(i){
			typeIds[i] = $(this).data("id");
			sorts[i] = i + 1;
		});
		cAjax({
			url: '/web/home/cooperater/saveTypeSorts',
			type:'post',
			data: {'typeIds':typeIds,'sorts':sorts},
			success:function(obj){
				greeting({msg:"保存顺序成功"});
			},
			error: function(obj) {
			}
		});
	});

	/*
	 * 拖放操作
	 */
	$("#custom-tools").draggable({
		containment: 'section.content',
		handle: '.dragbar'
	});

	function isOnHomePage($ele) {
		var onHomePageIds = [];
		$('.cooperater-on-homepage .preview').each(function(){
			onHomePageIds.push($(this).attr('data-id'));
		});
		var curId = $ele.attr('data-id');
		if(onHomePageIds.indexOf(curId) > -1 ) {
			return true;
		} else {
			return false;
		}
	}

	$( ".cooperater-on-homepage .home-item" ).droppable({
		drop: function( event, ui ) {
			var $this = $(this);
			var dragger = ui.draggable;
			if(isOnHomePage($(ui.draggable))) {
				greeting({
					title: '提示',
					msg: '这个合作伙伴已被添加到首页,不能重复添加'
				});	
			} else {
				$(this).html($(ui.draggable).clone().removeClass('dropable'));
			}
		},
		tolerance: 'fit',
		accept: '.dropable'
	})
	$( ".cooperater-on-homepage" ).sortable();

	$(".cooperater-type-container").sortable({
		axis: 'y',
		handle: '.dragbar',
		helper: 'clone'
	});

	$('.preview-container').sortable({
		helper: 'clone'
	});

});
